package fusion;

import java.io.*;

public class FusionUtil {
    public static void BugOn(boolean condition) {
        if(condition) {
            String s = "Quack! ";
            s += "(" + Thread.currentThread().getName() + ") ";
            s += "" + new Throwable().getStackTrace()[1].getFileName() + " ";
            s += "" + new Throwable().getStackTrace()[1].getLineNumber() + " ";
            System.out.println(s);
            while(true);
        }
    }
    public static Object ByteArray2Object(byte[] b) {
        Object ret = null;
        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        ObjectInputStream ois;

        //System.err.println("ba2o obj size: " + b.length);
        for(int i = 0; i < b.length; i++) {
            //System.err.println("ba2o[i]: " + b[i]);
        }
        if(b == null || b.length == 0) return ret;

        try {
            ois = new ObjectInputStream(bis);
            ret = ois.readObject();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
        return ret;
    }
    public static byte[] Object2ByteArray(Serializable obj) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
        }
        catch(IOException e) {
        }
        byte[] ret = baos.toByteArray();
        //System.err.println("o2ba obj size: " + ret.length);
        for(int i = 0; i < ret.length; i++) {
            //System.err.println("o2ba[i]: " + ret[i]);
        }
        return ret;
    }
    public static byte[] IntArray2ByteArray(int[] v, int length) {
        byte[] ret = new byte[length];

        //System.err.println("ia2ba size: " + length);
        for(int i = 0; i < length; ++i) {
            //System.err.println("ia2ba[i]: " + v[i]);
            int temp = v[i / 4] >> (3 - (i % 4)) * 8;
            temp &= 0xFF;
            ret[i] = (byte) temp;
        }
        return ret;

    }

    public static int[] ByteArray2IntArray(byte[] v) {
        if(v.length == 0) return null;
        int size = v.length / 4;
        if(v.length % 4 != 0) size++;

        int[] ret  = new int[size]; 
        //System.err.println("ba2ia size: " + v.length);
        for(int i = 0; i < ret.length; ++i) {
            ret[i] = 0;
        }


        for(int i = 0; i < v.length; ++i) {
            ret[i / 4] <<= 8;
            ret[i / 4] += (0xFF & v[i]);
        }
        if(v.length % 4 != 0) {
            ret[ret.length - 1] <<= 8 * (4 - (v.length % 4));
        }
        for(int i = 0; i < ret.length; ++i) {
            //System.err.println("ba2ia[i]: " + ret[i]);
        }
        return ret;
    }
}
